package com.pengtu.gsj.service.impl.check.qtwj;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.check.qtwj.CompleteWorkService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.utils.MathsUtils;

@Service
@Transactional
public class CompleteWorkServiceImpl implements CompleteWorkService{

	@Autowired
	public SystemManageService systemManageService;
	@Autowired
	public CheckTableService checkTableService;
	
	@Override
	public Map<String, Object> getCompleteWorks(String startTime, String endTime, CheckTable checkTable, String tag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Attachment> list = new ArrayList<Attachment>();
		List<Double> resLists = new ArrayList<Double>();
		
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double yearFull = Double.parseDouble((String)jsonObject.get("yearFull"));  //表格总分
		double firstStepScore = Double.parseDouble((String)jsonObject.get("firstStepScore"));  //及时性
		double secondStepScore = Double.parseDouble((String)jsonObject.get("secondStepScore"));  //是否落实进度
		double thirdStepScore = Double.parseDouble((String)jsonObject.get("thirdStepScore"));  //完成质量
		double fourthStepScore = Double.parseDouble((String)jsonObject.get("fourthStepScore"));  //其他方面
		double tableFull = yearFull;
		double total = yearFull;
		double percentage = 0;
		
		//根据时间、标签查询是否有附件
		list = systemManageService.getCheckAttachments(startTime, endTime, tag);
		//借用percent保存检查结果
		percentage = firstStepScore + secondStepScore + thirdStepScore + fourthStepScore;
		//根据条件进行算分
		if ( 4 == percentage) {
			total = yearFull;
		} else if (3 == percentage) {
			total = yearFull * 0.6;
		} else if (2 == percentage) {
			total = yearFull * 0.4;
		} else {
			total = 0;
		}
		//将检查结果返回前端
		resLists.add(firstStepScore);
		resLists.add(secondStepScore);
		resLists.add(thirdStepScore);
		resLists.add(fourthStepScore);
		percentage = MathsUtils.divDouble(total*100, tableFull, 4);
		
		//只有当系统完善度和检查得分不相等的情况下才更新数据  避免每次搜索都更新数据
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, true);
		map.put("att", list);
		map.put("resLists", resLists);
		map.put("percent", percentage);
		map.put("score", checkTable.getTestFull());
		map.put("checkTable", checkTable);
		return map;
	}

}
